/*
 * @lc app=leetcode.cn id=2 lang=javascript
 *
 * [2] 两数相加
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
    let carry = 0
    let result = new ListNode()
    let sum = result
    let temp = 0
    let first = true
    while (l1 || l2) {
        if (!first) {
            sum.next = new ListNode()
            sum = sum.next
        }
        let num1 = l1 ? l1.val : 0
        let num2 = l2 ? l2.val : 0
        let add = (carry + num1 + num2) % 10
        carry = parseInt((carry + num1 + num2) / 10) // 进位
        temp = carry
        sum.val = add
        if (l1) l1 = l1.next
        if (l2) l2 = l2.next
        first = false
    }
    console.log(temp)
    if (temp) sum.next = new ListNode(temp)
    console.log(result)
    return result
};
// @lc code=end
// @after-stub-for-debug-begin
module.exports = addTwoNumbers;
// @after-stub-for-debug-end